<template>
  <div style="padding-bottom: 10px">
    <el-input
      style="width: 240px"
      v-model="searchQuery"
      placeholder="输入地点名称"
    />
    <el-button style="margin-left: 8px" type="primary" @click="searchLocation"
      >搜索</el-button
    >
    <div style="margin-bottom: 8px"></div>

    <div ref="mapContainer" class="map-container"></div>
    <p v-if="currentCoordinates">当前位置: {{ currentCoordinates }}</p>
    <p v-if="formattedAddress">详细地址: {{ formattedAddress }}</p>
    <!-- <p v-if="searchedLocation">搜索结果: {{ searchedLocation }}</p> -->
    <div style="width: 100%">
      <el-button style="float: right" type="primary" @click="clickChildw"
        >确认</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, onUpdated } from "vue";
import { load } from "@amap/amap-jsapi-loader";
import { getMapmesageInfo } from "@/api/getMapmesage";
import axios from "axios";

import { defineEmits } from "vue";
// 使用defineEmits创建名称，接受一个数组
const emit = defineEmits(["clickChild"]);
const clickChildw = () => {
  //传递给父组件

  let adrasvalue = {
    locationval: "",
    lng: "",
    lat: "",
  };

  adrasvalue.locationval = formattedAddress.value;
  adrasvalue.lng = lngvalue.value;
  adrasvalue.lat = latvalue.value;

  emit("clickChild", adrasvalue);
};

// 高德地图API的Key，请替换为您的实际密钥
const apiKey = import.meta.env.VITE_MAPAPIKEY; // 注意：这里仅用于地图界面展示的API Key
const apiKey2 = import.meta.env.VITE_MAPAPIKEY2; // 注意：这里仅用于地图搜索和获取地理信息


// 地图容器的引用
const mapContainer = ref(null);
// 当前位置的经纬度信息
const currentCoordinates = ref("");
// 当前位置的详细地址信息
const formattedAddress = ref("");
// 搜索框的值
const searchQuery = ref("");
// 搜索结果的位置信息
const searchedLocation = ref("");
// 错误信息
const errorMessage = ref("");
// 地图实例
let map;
// 标记实例
let marker;

let lngvalue = ref("");
let latvalue = ref("");

// 初始化地图和获取当前位置的逻辑
async function initMap() {
  try {
    const AMap = await load({
      key: apiKey,
      version: "2.0",
      plugins: ["AMap.Geolocation", "AMap.Geocoder", "AMap.PlaceSearch"],
    });

    // 初始化地图对象
    map = new AMap.Map(mapContainer.value, {
      zoom: 10,
      center: [116.397428, 39.90923],
    });

    // 获取当前位置
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0,
      convert: true,
    });

    geolocation.getCurrentPosition((status, result) => {
      if (status === "complete") {
        onComplete(result, map, AMap);
      } else {
        onError(result);
      }
    });

    // 添加鼠标点击事件监听器
    map.on("click", handleMapClick);
  } catch (error) {
    console.error("加载高德地图失败:", error);
  }
}

function onComplete(data, map, AMap) {
  const lnglat = data.position;
  currentCoordinates.value = `经度: ${lnglat.lng}, 纬度: ${lnglat.lat}`;

  lngvalue.value = lnglat.lng;
  latvalue.value = lnglat.lat;

  // 更新地图中心到当前位置
  map.setCenter([lnglat.lng, lnglat.lat]);

  // 在地图上添加标记
  marker = new AMap.Marker({
    position: [lnglat.lng, lnglat.lat],
    title: "当前位置",
  });
  map.add(marker);

  // 使用逆地理编码插件获取详细地址
  // const geocoder = new AMap.Geocoder();
  // geocoder.getAddress([lnglat.lng, lnglat.lat], (status, result) => {
  //   if (status === "complete" && result.regeocode) {
  //     const addressComponents = result.regeocode.addressComponent;
  //     const addressDetail = {
  //       country: addressComponents.country || "",
  //       province: addressComponents.province || "",
  //       city: addressComponents.city || "",
  //       district: addressComponents.district || "",
  //       street: addressComponents.streetNumber.street || "",
  //       number: addressComponents.streetNumber.number || "",
  //     };
  //     formattedAddress.value = `${addressDetail.country}${addressDetail.province}${addressDetail.city}${addressDetail.district}${addressDetail.street}${addressDetail.number}`;
  //   } else {
  //     console.error("获取详细地址失败:", result);
  //   }
  // });
}

function onError(data) {
  console.error("获取当前位置失败:", data);
}

// 实现位置搜索功能
async function searchLocation() {
  try {
    if (!searchQuery.value.trim()) {
      throw new Error("请输入搜索关键词");
    }

    const response = await axios.get("https://restapi.amap.com/v3/place/text", {
      params: {
        key: apiKey2,
        keywords: searchQuery.value,
        city: "全国",
        output: "json",
      },
    });

    if (response.data.status === "0") {
      throw new Error(response.data.info || "请求失败");
    }

    const poi = response.data.pois[0]; // 假设只取第一个搜索结果
    if (!poi) {
      throw new Error("未找到相关地点");
    }

    const { location, name, address } = poi;
    const [lng, lat] = location.split(",").map(Number);

    // 更新地图中心到搜索结果位置
    map.setCenter([lng, lat]);

    // 更新标记位置
    if (marker) {
      marker.setPosition([lng, lat]);
    } else {
      marker = new AMap.Marker({
        position: [lng, lat],
        title: name,
      });
      map.add(marker);
    }

    searchedLocation.value = `${name} - ${address}`;
  } catch (error) {
    errorMessage.value = error.message;
    console.error("搜索地点失败:", error);
  }
}

// 处理地图点击事件
function handleMapClick(e) {
  const { lng, lat } = e.lnglat;
  currentCoordinates.value = `经度: ${lng}, 纬度: ${lat}`;

  lngvalue.value = lng;
  latvalue.value = lat;
  getMapmesageInfofun(lng, lat);
  // 更新标记位置
  if (marker) {
    marker.setPosition([lng, lat]);
  } else {
    marker = new AMap.Marker({
      position: [lng, lat],
      title: "点击位置",
    });
    map.add(marker);
  }

  // // 使用逆地理编码插件获取详细地址
  // const geocoder = new AMap.Geocoder();
  // geocoder.getAddress([lng, lat], (status, result) => {
  //   if (status === "complete" && result.regeocode) {
  //     const addressComponents = result.regeocode.addressComponent;
  //     const addressDetail = {
  //       country: addressComponents.country || "",
  //       province: addressComponents.province || "",
  //       city: addressComponents.city || "",
  //       district: addressComponents.district || "",
  //       street: addressComponents.streetNumber.street || "",
  //       number: addressComponents.streetNumber.number || "",
  //     };
  //     formattedAddress.value = `${addressDetail.country}${addressDetail.province}${addressDetail.city}${addressDetail.district}${addressDetail.street}${addressDetail.number}`;
  //   } else {
  //     console.error("获取详细地址失败:", result);
  //   }
  // });
}

onMounted(() => {
  initMap();
});

const getMapmesageInfofun = async (lng, lat) => {
  let massege = await getMapmesageInfo(
    apiKey2,
    lng,
    lat
  );
  formattedAddress.value = massege.data.regeocode.formatted_address;
};

setTimeout(() => {
  getMapmesageInfofun(lngvalue.value, latvalue.value);
}, 3000);
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 500px;
}
.map {
  width: 100%;
  height: 100%;
}
.error {
  color: red;
}
</style>
